<template>
  <div class="addData-page">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      size="medium"
      label-width="160px"
      class="addData-page-form"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="数据源名称" prop="name">
            <el-input
              v-model="formData.name"
              placeholder="请输入数据源名称"
              show-word-limit
              clearable
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="接口地址" prop="url">
            <el-input
              v-model="formData.url"
              placeholder="请输入接口地址（例 http://www.usmartww.com.cn）"
              show-word-limit
              clearable
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="请求方法" prop="method">
            <el-radio-group v-model="formData.method" size="medium">
              <el-radio
                v-for="(item, index) in methodOptions"
                :key="index"
                :label="item.value"
                :disabled="item.disabled"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="超时时间" prop="timeout">
            <el-input-number
              :min="0"
              v-model="formData.timeout"
              placeholder="请输入超时时间"
            ></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="参数">
            <el-button
              class="addData-small-button"
              type="primary"
              icon="el-icon-plus"
              @click="addParams"
            >
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row
        :gutter="10"
        v-for="(item, index) in formData.parameter"
        :key="index"
      >
        <el-col :span="11">
          <el-form-item label="参数名">
            <el-input
              v-model="item.key"
              placeholder="请输入参数名"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="参数值">
            <el-input
              v-model="item.value"
              placeholder="请输入参数值"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-button
            class="addData-small-button"
            size="small"
            type="danger"
            icon="el-icon-minus"
            @click="removeParams(index)"
          >
          </el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="数据源描述">
            <el-input
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 10 }"
              placeholder="请输入数据源描述"
              v-model="formData.description"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="是否定时任务" prop="scheduled">
            <el-switch v-model="formData.scheduled"></el-switch>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="!formData.scheduled">
        <el-col :span="24">
          <el-form-item label="导出接口地址" prop="outputUrl">
            <el-input
              v-model="formData.outputUrl"
              placeholder="请输入导出接口地址"
              clearable
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 定时频率 -->
      <el-row v-if="formData.scheduled">
        <el-col :span="24">
          <el-form-item
            label="定时频率"
            class="addData-form-timeFrequency"
            prop="frequency"
          >
            <el-button @click="open">打开cron表达式生成器</el-button>
            <CronUi ref="CronUiRef" @cronResult="resultValue"></CronUi>
            <p>最终生成的表达式为：{{ formData.frequency }}</p>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 起止时间  -->
      <el-row v-if="formData.scheduled">
        <el-col :span="24">
          <el-form-item label="起止时间" prop="startEndTime">
            <el-date-picker
              v-model="formData.startEndTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="请输入开始时间"
              end-placeholder="请输入结束时间"
              unlink-panels
              style="width: 100%"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item
            label="数据转换统计规则"
            class="addData-form-pretreatmentCode"
          >
            <el-select
              multiple
              collapse-tags
              v-model="formData.pretreatmentCodeId"
              placeholder="请选择脚本库"
            >
              <el-option
                v-for="item in formData.pretreatmentCodeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <el-button type="primary" @click="goNewPage">新增</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="接口测试">
            <el-button type="primary" @click="portTest">测试</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="测试结果">
            <el-input
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 10 }"
              placeholder='例 {"code":200,"message":"操作成功","result":{"totalCount":0,"pageSize":10,"totalPage":0,"currPage":1,"list":[]}}'
              v-model="formData.portTestResult"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 结果值映射 -->
      <map-relation
        :mapRelation="mapRelation"
        @newAddMap="newAddMap"
      ></map-relation>
      <el-row v-if="formData.scheduled">
        <el-col :span="24">
          <el-form-item label="存储位置" prop="storageLocation">
            <el-radio-group v-model="formData.storageLocation" size="medium">
              <el-radio
                v-for="(item, index) in storageLocationOptions"
                :key="index"
                :label="item.value"
                :disabled="item.disabled"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item
            label="是否清空表再插入数据"
            v-if="formData.scheduled && formData.storageLocation == 1"
            prop="truncateTable"
          >
            <el-switch v-model="formData.truncateTable"></el-switch>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item
        label="列映射关系"
        v-if="formData.scheduled && formData.storageLocation == 1"
      >
        <el-button type="primary" @click="addDatabaseDialog"> 配置 </el-button>
        <span v-if="formData.tableName">
          数据库表：{{ formData.tableName }}
        </span>
        <span v-else> 暂无配置表</span>
      </el-form-item>
      <el-form-item
        class="column-table-item"
        label=""
        v-if="
          formData.scheduled &&
          formData.tableName &&
          formData.storageLocation == 1
        "
      >
        <gz-table :config="config"> </gz-table>
      </el-form-item>
      <el-form-item
        label="RedisKey"
        v-if="formData.scheduled && formData.storageLocation == 2"
      >
        <el-input
          v-model="formData.redisKey"
          placeholder="请输入redisKey"
        ></el-input>
      </el-form-item>
      <el-row>
        <el-col :span="24">
          <el-form-item size="large">
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
  <!-- 列映射关系 -->
  <el-dialog
    title="配置"
    width="441px"
    v-model="dialogVisible"
    :close-on-click-modal="false"
    v-if="dialogVisible"
    @opened="opened"
  >
    <column-map-relation
      ref="columnMapRef"
      @tableSuccessBuild="tableSuccessBuild"
    ></column-map-relation>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="configSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import gzTable from "@/components/table/index.vue";
import columnMapRelation from "@/views/addData/components/columnMapRelation.vue";
import mapRelation from "@/views/addData/components/mapRelation.vue";
import CronUi from "@/components/corn/cron-ui/index";

import { reactive, toRefs, ref, watch, onMounted } from "vue";

const validateFrequency = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请设置定时频率"));
  } else {
    callback();
  }
};
export default {
  name: "addDataPage",
  components: {
    gzTable,
    columnMapRelation,
    mapRelation,
    CronUi,
  },
  setup() {
    const columnMapRef = ref(null);
    const CronUiRef = ref(null);
    const formRef = ref(null);
    const databaseRef = ref(null);
    const dialogVisible = ref(false);
    const state = reactive({
      config: {
        // 表格样式
        style: {
          stripe: true,
          border: true,
          size: "mini",
          maxHeight: 700,
        },
        loading: false,
        // 列
        column: [
          {
            prop: "key",
            label: "列名",
            width: 500,
          },
          {
            prop: "value",
            label: "值映射",
            width: 600,
          },
        ],
        tableData: [],
      },
      mapRelation: {
        labelName: "结果值映射",
        keyName: "列名",
        placeholderKeyName: "请输入列名",
        valueName: "值映射",
        placeholderValueName: "请输入值映射",
      },
      formData: {
        truncateTable: false, // 是否清空表再插入数据
        columnRelationshipTableData: [], // 列映射关系表格数据
        name: "",
        description: "",
        pretreatmentCodeList: [], // 数据转换 脚本库集合
        pretreatmentCodeId: [], // 数据转换 脚本库id集合
        columnRelationshipId: "",
        resultRelationship: "",
        portTestResult: "", // 接口测试结果
        cronExpression: "",
        url: "",
        method: "GET",
        timeout: 10,
        parameter: [],
        scheduled: true,
        outputUrl: "",
        frequency: "",
        startEndTime: [],
        startTime: null,
        endTime: null,
        storageLocation: 1,
        tableName: "",
        tableId: "",
        redisKey: "",
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入数据源名称",
            trigger: "blur",
          },
        ],
        url: [
          {
            required: true,
            message: "请输入接口地址",
            trigger: "blur",
          },
        ],
        method: [
          {
            required: true,
            message: "请求方法不能为空",
            trigger: "change",
          },
        ],
        timeout: [
          {
            required: true,
            message: "请输入超时时间",
            trigger: "blur",
          },
        ],
        outputUrl: [
          {
            required: true,
            message: "请输入导出接口地址",
            trigger: "blur",
          },
        ],
        frequency: [
          {
            required: true,
            validator: validateFrequency,
          },
        ],
        startEndTime: [
          {
            required: true,
            message: "起止时间不能为空",
            trigger: "change",
          },
        ],
        storageLocation: [
          {
            required: true,
            message: "存储位置不能为空",
            trigger: "change",
          },
        ],
      },
      methodOptions: [
        {
          label: "GET",
          value: "GET",
        },
        {
          label: "POST",
          value: "POST",
        },
      ],
      storageLocationOptions: [
        {
          label: "数据库",
          value: 1,
        },
        {
          label: "Redis",
          value: 2,
        },
      ],
    });
    watch(
      () => [state.formData.scheduled, state.formData.storageLocation],
      ([scheduledValue, storageLocationValue]) => {
        // scheduledValue true:导出接口地址清空 false:定时频率,起止时间,存储位置归数据库,列映射关系id清空
        if (scheduledValue) {
          getScriptLibrary(); // 获取脚本库
          state.formData.outputUrl = "";
        } else {
          state.formData.frequency = "";
          state.formData.startEndTime = "";
          state.formData.storageLocation = 1;
          state.formData.tableName = "";
          state.formData.columnRelationshipId = "";
          state.formData.tableId = "";
          state.formData.redisKey = "";
          state.config.tableData = [];
        }
        // storageLocationValue 1:数据库 2:Redis
        if (storageLocationValue === 1) {
          state.formData.redisKey = "";
        }
        if (storageLocationValue === 2) {
          state.formData.tableId = "";
          state.formData.tableName = "";
          state.formData.columnRelationshipId = "";
        }
      }
    );
    onMounted(() => {
      getScriptLibrary(); // 获取脚本库
    });
    // 获取脚本库
    const getScriptLibrary = async () => {
      state.formData.pretreatmentCodeList = await vm.$store.dispatch(
        "GET_SCRIPT"
      );
    };
    // 添加参数
    const addParams = () => {
      state.formData.parameter.push({
        key: "",
        value: "",
      });
    };
    // 删除参数
    const removeParams = (index) =>
      removeRowData(state.formData.parameter, index);
    // 打开 列映射关系弹框
    const addDatabaseDialog = () => {
      dialogVisible.value = true;
    };
    // 删除行数据
    const removeRowData = (data, index) => {
      return data.splice(index, 1);
    };
    // 弹窗打开
    const opened = () => {
      // 请求接口
      // columnMapRef.value.getDataTableList();
    };
    // 跳转到 Java代码新页面
    const goNewPage = () => {
      // window.open("../../.././resources/templates/index.html", "_blank");
      vm.$router.push("/addJavaScript");
    };
    // 接口测试
    const portTest = async () => {
      if (!state.formData.url) {
        vm.$message.warning("请输入接口地址！");
        return false;
      }
      let result = await vm.$store.dispatch("PORT_TEST", {
        url: state.formData.url,
        method: state.formData.method,
        timeout: state.formData.timeout,
        parameter: vm.$tool.arrayToObj(state.formData.parameter),
        pretreatmentCodeIds: state.formData.pretreatmentCodeId.map(
          (pItem, pIndex) => {
            return {
              id: pItem,
              priority: pIndex,
            };
          }
        ),
      });
      state.formData.portTestResult = JSON.stringify(result);
    };
    // 结果值映射 确定回调
    const newAddMap = async (data) => {
      state.formData.resultRelationship = data ? JSON.stringify(data) : "";
    };
    // 成功新建数据库表 后回调
    const tableSuccessBuild = () => {
      // 调用 获取数据库表 方法
      columnMapRef.value.getDataTableList();
    };
    // 列映射关系 配置确定 回调
    const configSubmit = async () => {
      let tableId = columnMapRef.value.form.tableName;
      let columnData = columnMapRef.value.config.tableData;

      if (!tableId) {
        vm.$message.warning("请选择数据库表！");
        return false;
      }
      state.formData.tableName = columnMapRef.value.selectTableName;
      let relationContent = vm.$tool.arrayToObj(columnData);
      let result = await vm.$store.dispatch(
        "ADD_RESULT_RELATIONSHIP",
        relationContent
      );
      if (result && result.id) {
        state.config.tableData = columnData;
        state.formData.columnRelationshipId = result.id;
        vm.$message.success("列映射关系配置成功！");
        state.formData.tableId = tableId;
        dialogVisible.value = false;
      }
    };
    // 提交
    const submitForm = () => {
      formRef.value.validate((valid) => {
        if (!valid) return;
        if (!state.formData.scheduled) {
          state.formData.startTime = state.formData.endTime = "";
        } else {
          let [startTime, endTime] = state.formData.startEndTime;
          state.formData.startTime = vm.$tool.formatDateTime(startTime);
          state.formData.endTime = vm.$tool.formatDateTime(endTime);
        }

        // 处理定时频率传参
        vm.$axios
          .post("/api/v1/datasource/addDataSource", {
            truncateTable: state.formData.truncateTable,
            name: state.formData.name,
            url: state.formData.url,
            parameter:
              state.formData.parameter.length > 0
                ? JSON.stringify(vm.$tool.arrayToObj(state.formData.parameter))
                : "",
            method: state.formData.method,
            timeout: state.formData.timeout,
            scheduled: state.formData.scheduled,
            outputUrl: state.formData.outputUrl,
            frequency: state.formData.frequency,
            startTime: state.formData.startTime,
            endTime: state.formData.endTime,
            tableName: state.formData.tableName,
            resultRelationship: state.formData.resultRelationship,
            columnRelationshipId: state.formData.columnRelationshipId,
            tableId: state.formData.tableId,
            redisKey: state.formData.redisKey,
            description: state.formData.description,
            pretreatmentCodeId: state.formData.pretreatmentCodeId.map(
              (v, i) => {
                return { id: v, priority: i };
              }
            ),
          })
          .then(() => {
            vm.$message.success("添加数据源成功！");
            vm.$router.push("/manageData");
          })
          .catch(() => {});
      });
    };
    // 重置
    const resetForm = () => {
      formRef.value.resetFields();
    };
    // 打开cron表达式
    const open = () => {
      CronUiRef.value.dialogVisible = true;
    };
    // cron表达式 确定回调
    const resultValue = (data) => {
      state.formData.frequency = data;
    };

    //
    const removeClick = (rowData) => {
      // 获取当前列索引
      let findIndex = state.config.tableData.findIndex(
        (tItem) => tItem.key == rowData.key
      );
      if (findIndex > -1) {
        state.config.tableData.splice(findIndex, 1);
      }
    };
    return {
      columnMapRef,
      formRef,
      databaseRef,
      CronUiRef,
      open,
      resultValue,
      dialogVisible,
      ...toRefs(state),
      getScriptLibrary,
      addParams,
      removeParams,
      addDatabaseDialog,
      goNewPage,
      newAddMap,
      tableSuccessBuild,
      configSubmit,
      submitForm,
      resetForm,
      opened,
      portTest,
      removeClick,
    };
  },
};
</script>

<style scoped>
.addData-page-form {
  width: 100%;
}
.addData-small-button {
  padding: 11px 15px;
}
.addData-form-timeFrequency .el-select {
  margin: 0 10px 10px 0;
}
.addData-form-timeFrequency .addData-form-timeFrequency-corn {
  display: flex;
  align-items: center;
}
.addData-form-timeFrequency .addData-form-timeFrequency-corn span {
  width: 120px;
  color: #606266;
}
.addData-form-pretreatmentCode >>> .el-input__inner {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}
.addData-form-pretreatmentCode >>> .el-button {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  margin-top: -1px;
}
/* .column-table-item >>> .el-table__header {
  width: 100% !important;
}
.column-table-item >>> .el-table__body {
  width: 100% !important;
} */
</style>
